﻿using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using HandyControl.Controls;
using WWLauncher.Constant;
using WWLauncher.Util;
using WWLauncher.View.Other;
using WWLauncher.ViewModel;

namespace WWLauncher.View.UserControls.PannelCard
{
    /// <summary>
    /// RightCardControl.xaml 的交互逻辑
    /// </summary>
    public partial class RightCardControl : UserControl
    {
        private readonly MainViewModel viewModel = MainViewModel.Instance();
        public ProcessUtil process = new();
        public MainWindow ParentWindow { get; set; }

        public RightCardControl()
        {
            InitializeComponent();
            this.Loaded += RightCardControl_Loaded;
        }

        private void RightCardControl_Loaded(object sender, RoutedEventArgs e)
        {
            PDDialog.ParentWindow = ParentWindow;
        }




        private void Icon_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (viewModel.AppConfig.DoubleOpen)
            {
                IconClick(sender, e);
            }
        }

        private void Icon_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (!viewModel.AppConfig.DoubleOpen)
            {
                IconClick(sender, e);
            }
        }

        /// <summary>
        /// 图标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void IconClick(object sender, MouseButtonEventArgs e)
        {
            if (!RunTimeStatus.SearchBoxHided300) return;
            ProcessEnum pp = ProcessEnum.Success;
            if (viewModel.AppConfig.DoubleOpen && e.ClickCount >= 2)
            {
                IconInfo icon = (IconInfo)((Panel)sender).Tag;

                pp = process.StartIconApp(icon);
            }
            else if (!viewModel.AppConfig.DoubleOpen && e.ClickCount == 1)
            {
                IconInfo icon = (IconInfo)((Panel)sender).Tag;

                pp = process.StartIconApp(icon);

            }
            if (pp != ProcessEnum.Success)
            {
                Growl.Error(pp.GetDescription(), "MainWindowGrowl");
            }
        }

        /// <summary>
        /// 管理员身份启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AdminStart_Click(object sender, RoutedEventArgs e)
        {
            IconInfo icon = (IconInfo)((MenuItem)sender).Tag;
            process.StartIconApp(icon, false, true);
        }

        /// <summary>
        /// 打开文件所在位置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowInExplore_Click(object sender, RoutedEventArgs e)
        {
            IconInfo icon = (IconInfo)((MenuItem)sender).Tag;
            if(icon.StartType== IconStartType.OpenWithBrowser)
            {
                Growl.Fatal ("该应用无法实现打开。", "MainWindowGrowl");
                return;
            }
            process.ShowInExplore(icon);
        }

        /// <summary>
        /// 拖拽添加项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Wrap_Drop(object sender, DragEventArgs e)
        {
            Array dropObject = (Array)e.Data.GetData(DataFormats.FileDrop);
            if (dropObject == null) return;
            foreach (object obj in dropObject)
            {
                string path = (string)obj;
                IconInfo iconInfo = CommonCode.GetIconInfoByPath(path).To();
                viewModel.MenuList[viewModel.SelectedMenuIndex].IconList.Add(iconInfo);
            }
            CommonCode.SortIconList();
            ConfigUtil.SaveAppData();
        }

        /// <summary>
        /// 从列表删除图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RemoveIcon_Click(object sender, RoutedEventArgs e)
        {
            viewModel.MenuList[viewModel.SelectedMenuIndex].IconList.Remove((IconInfo)((MenuItem)sender).Tag);
        }

        private void SystemMenu_Click(object sender, RoutedEventArgs e)
        {
            IconInfo icon = (IconInfo)((MenuItem)sender).Tag;
            DirectoryInfo[] folders = new DirectoryInfo[1];
            folders[0] = new DirectoryInfo(icon.TargetPath);
            ShellContextMenu scm = new ShellContextMenu();
            System.Drawing.Point p = System.Windows.Forms.Cursor.Position;
            p.X -= 80;
            p.Y -= 80;
            scm.ShowContextMenu(folders, p);
        }

        /// <summary>
        /// 弹出Icon属性修改面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Property_Click(object sender, RoutedEventArgs e)
        {
            IconInfo info = (IconInfo)((MenuItem)sender).Tag;
            switch (info.StartType)
            {
                case IconStartType.OpenWithBrowser:
                    var urlDialog = new IconInfoUrlDialog(info);
                    urlDialog.ShowDialog();
                    break;
                default:
                    var dialog = new IconInfoDialog(info);
                    dialog.ShowDialog();
                    break;
            }
        }


        private void IconApp_Click(object sender, RoutedEventArgs e)
        {
            var iconDialog = new IconInfoDialog();
            iconDialog.ShowDialog();
        }

        /// <summary>
        /// 添加URL项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddUrlIcon_Click(object sender, RoutedEventArgs e)
        {
            IconInfoUrlDialog urlDialog = new IconInfoUrlDialog();
            urlDialog.ShowDialog();
        }

        /// <summary>
        /// 添加系统项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddSystemIcon_Click(object sender, RoutedEventArgs e)
        {
            SystemItemWindow.Show();
        }

        public void VisibilitySearchCard(Visibility vb)
        {
            VerticalCard.Visibility = vb;
            if (vb == Visibility.Visible)
            {
                WrapCard.Visibility = Visibility.Collapsed;
            }
            else
            {
                WrapCard.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// 搜索Card点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VerticalCard_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //隐藏搜索框
            if (RunTimeStatus.SearchBoxShow)
            {
                ParentWindow.HidedSearchBox();
            }
        }


        /// <summary>
        /// 锁定/解锁主面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LockAppPanel_Click(object sender, RoutedEventArgs e)
        {
            RunTimeStatus.LockAppPanel = !RunTimeStatus.LockAppPanel;
        }

        private void WrapCard_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (RunTimeStatus.LockAppPanel)
            {
                CardLockCM.Header = "解锁主面板";
            }
            else
            {
                CardLockCM.Header = "锁定主面板";
            }
        }



        private void PDDialog_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (PDDialog.Visibility == Visibility.Visible)
            {
                RunTimeStatus.ShowMenuPasswordbox = true;
                PDDialog.ClearVal();
                PDDialog.ErrorMsg.Visibility = Visibility.Collapsed;
                PDDialog.PasswordGrid.Visibility = Visibility.Visible;
                PDDialog.HintGrid.Visibility = Visibility.Collapsed;
                PDDialog.count = 0;
                PDDialog.SetFocus();
            }
            else
            {
                RunTimeStatus.ShowMenuPasswordbox = false;
                PDDialog.ClearVal();
                ParentWindow.Focus();
            }
        }

        /// <summary>
        /// 菜单结果icon 列表鼠标滚轮预处理时间  
        /// 主要使用自定义popup解决卡顿问题解决卡顿问题
        /// 以及滚动条首尾切换菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IconListBox_MouseWheel(object sender, MouseWheelEventArgs e)
        {

            //控制在滚动时不显示popup 否则会在低GPU性能机器上造成卡顿
            MyPoptip.IsOpen = false;
            if (RunTimeStatus.IconlistMouseWheel)
            {
                RunTimeStatus.MouseWheelWaitMs = 500;
            }
            else
            {
                RunTimeStatus.IconlistMouseWheel = true;

                new Thread(() =>
                {
                    while (RunTimeStatus.MouseWheelWaitMs > 0)
                    {
                        Thread.Sleep(1);
                        RunTimeStatus.MouseWheelWaitMs -= 1;
                    }
                    if (RunTimeStatus.MouseEnterIcon)
                    {
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            MyPoptip.IsOpen = true;
                        }));
                    }
                    RunTimeStatus.MouseWheelWaitMs = 100;
                    RunTimeStatus.IconlistMouseWheel = false;
                }).Start();
            }

            //修改菜单时不切换菜单
            if (RunTimeStatus.IsMenuEdit) return;


            //切换菜单
            System.Windows.Controls.ScrollViewer scrollViewer = sender as System.Windows.Controls.ScrollViewer;
            if (scrollViewer == null)
            {
                //在card 上获取的事件
                scrollViewer = ScrollUtil.FindSimpleVisualChild<System.Windows.Controls.ScrollViewer>(IconListBox);
            }
            if (e.Delta < 0)
            {
                int index = ParentWindow.LeftCard.MenuListBox.SelectedIndex;
                if (ScrollUtil.IsBootomScrollView(scrollViewer))
                {
                    if (index < ParentWindow.LeftCard.MenuListBox.Items.Count - 1)
                    {
                        index++;
                    }
                    else
                    {
                        index = 0;
                    }
                    ParentWindow.LeftCard.MenuListBox.SelectedIndex = index;
                    scrollViewer.ScrollToVerticalOffset(0);
                }
            }
            else if (e.Delta > 0)
            {
                if (ScrollUtil.IsTopScrollView(scrollViewer))
                {
                    int index = ParentWindow.LeftCard.MenuListBox.SelectedIndex;
                    if (index > 0)
                    {
                        index--;
                    }
                    else
                    {
                        index = ParentWindow.LeftCard.MenuListBox.Items.Count - 1;
                    }
                    ParentWindow.LeftCard.MenuListBox.SelectedIndex = index;
                    scrollViewer.ScrollToVerticalOffset(0);
                }
            }


        }

        /// <summary>
        /// menu结果ICON鼠标移动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuIcon_MouseMove(object sender, MouseEventArgs e)
        {
            //防止移动后不刷新popup content
            IconInfo info = (sender as Panel)?.Tag as IconInfo;
            MyPoptipContent.Text = info.ToolTip;
            MyPoptip.VerticalOffset = 30;
        }

       
    }
}
